<script setup>
import { ref, onBeforeMount, h, reactive } from 'vue'
import { NDataTable, NButton, NForm, NFormItem, NInput, NCard, NModal, NIcon, NSelect, useMessage } from 'naive-ui'
import { ApartmentOutlined, LockOutlined, CloudServerOutlined, ApiOutlined, UserOutlined } from '@vicons/antd'
import md5 from 'js-md5'
import http from '../http'

// 字段配置
const columns = [
  { title: '链接ID', key: 'lid' },
  { title: '主机', key: 'host' },
  { title: '名称', key: 'name' },
  { title: '端口', key: 'port' },
  { title: '用户', key: 'uid' },
  {
    title: '操作',
    key: 'action',
    render(row, index) {
      return h(NButton, { type: 'error', onClick: () => onRemoveLink(row.lid, index) }, { default: () => '删除' })
    }
  }
]

const data = ref([])

// 消息
const message = useMessage()


// 校验规则
const rules = {
  lid: { required: true, trigger: ['blur', 'change'], message: '请选择链接ID' },
  host: { required: true, trigger: 'blur', message: '请输入主机地址' },
  name: { required: true, trigger: 'blur', message: '请输入主机名称' },
  port: { required: true, trigger: 'blur', message: '请输入主机端口' },
  uid: { required: true, trigger: 'blur', message: '请输入用户' },
  password: { required: true, trigger: 'blur', message: '请输入密码' },
}

// 链接ID选项
const options = [
  { label: '核心账务系统', value: 'core' }
]

// 表单
const formRef = ref(null)

// 是否显示对话框
const showModal = ref(false)

// 关闭对话框
const onClose = () => {
  showModal.value = false
}

// 链接信息
const link = reactive({
  lid: '',
  host: '',
  port: '',
  uid: '',
  password: '',
})

// 新增链接
const onAddLink = (e) => {
  e.preventDefault()
  formRef.value.validate(err => {
    if (!err) {
      const password = md5(`${link.uid}-${link.password}`)
      http.post('/api/link/add', link).then(res => {
        if (res.data.status) {
          data.value.push({
            lid: link.lid,
            host: link.host,
            name: link.name,
            port: link.port,
            uid: link.uid,
            password: password,
          })
          showModal.value = false
          console.log('Link.onAddLink => 新增链接成功')
          message.success('新增链接成功')
        } else {
          console.log(`Link.onAddLink => 新增链接失败:${res.data.message}`)
          message.warning(res.data.message)
        }
      }).catch(err => {
        console.log(`Link.onAddlink => 新增链接错误：${err.message}`)
        message.warning(err.message)
      })
    } else {
      // 字段校验失败
      for (let row of err) {
        console.log(`字段校验失败：${row[0].message}`)
      }
    }
  })
}

// 链接删除
function onRemoveLink(lid, index) {
  http.delete(`/api/link/remove/${lid}`).then(res => {
    if (res.data.status) {
      console.log(`Link.onRemoveLink => 删除链接${lid}成功`)
      data.value.splice(index, 1)
      message.success(`删除链接${lid}成功`)
    } else {
      console.log(`Link.onRemoveLink => 删除链接${lid}失败：${res.data.message}`)
      message.warning(`${res.data.message}`)
    }
  }).catch(err => {
    console.warn(`Link.onRemoveLink => ${err}`)
    message.error(`${err}`)
  })
}

// 预加载数据
onBeforeMount(() => {
  http.get('/api/link/list').then(res => {
    console.log(`Link.onBeforeMount => 获取链接清单`)
    data.value = res.data
  }).catch(err => {
    console.warn(`Link.onBeforeMount => 获取链接清单失败`)
  })
})
</script>


<template>
  <n-data-table :data="data" :columns="columns"></n-data-table>
  <div class="btn"><n-button type="primary" @click="showModal = true">新增链接</n-button></div>

  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card style="width: 400px" title="新增链接" :bordered="false" aria-modal="true" closable @close="onClose"
      :segmented="{ content: true }" :footer-style="{ 'text-align': 'center' }">

      <n-form :rules="rules" label-placement="left" :label-width="70" ref="formRef" :model="link">
        <n-form-item label="链接ID" path="lid">
          <n-select v-model:value="link.lid" :options="options" placeholder="请选择链接ID">
            <template #prefix>
              <n-icon>
                <ApartmentOutlined />
              </n-icon>
            </template>
          </n-select>
        </n-form-item>
        <n-form-item label="主机" path="host">
          <n-input v-model:value="link.host" placeholder="请输入主机地址">
            <template #prefix>
              <n-icon>
                <CloudServerOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="名称" path="name">
          <n-input v-model:value="link.name" placeholder="请输入主机名称">
            <template #prefix>
              <n-icon>
                <CloudServerOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="端口" path="port">
          <n-input v-model:value="link.port" placeholder="请输入主机端口">
            <template #prefix>
              <n-icon>
                <ApiOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="用户" path="uid">
          <n-input v-model:value="link.uid" placeholder="请输入用户">
            <template #prefix>
              <n-icon>
                <UserOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input v-model:value="link.password" placeholder="请输入密码" type="password">
            <template #prefix>
              <n-icon>
                <LockOutlined />
              </n-icon>
            </template>
          </n-input>
        </n-form-item>
      </n-form>

      <template #footer>
        <n-button type="primary" @click="onAddLink" block size="large">新增链接</n-button>
      </template>
    </n-card>
  </n-modal>
</template>

<style scoped>
.btn {
  text-align: center;
  margin-top: 10px;
}
</style>